var stats = new liwe.module ( 'stats' );

stats.init = function ( module, evts )
{
	var events = [
		{ label: '(tutti)', value: '' }
	];
	if ( evts )
	{
		events.push ( { label: '(multipli)', value: '__all' } );
		evts.iterate ( function ( v, k )
		{
			events.push ( { label: k, value: v } );
		});
	}
	this.module = module;
	this.events = events;
};

stats.graph = function ( dest_div, type, res )
{
	var g = new WWL.graph ( dest_div );
	g.draw ( {
		type: type,
		theme: 'pastel',
		data: res.data,
		options: {
			labels: res.labels,
			minimum_value: 0
		}
	});
};

stats.form = function ( dest_div, dest_div_form, extras )
{
	var log_types = [
		{ label: 'Day', value: 'day' },
		{ label: 'Month', value: 'month' },
		{ label: 'Year', value: 'year' },
		{ label: 'Week', value: 'week' },
		{ label: 'Weekday', value: 'weekday' },
		{ label: 'Hour', value: 'hour' }
	];
	var gtypes = [
		{ label: 'Bar', value: 'Bar' },
		{ label: 'Line', value: 'Line' },
		{ label: 'Pie', value: 'Pie' }
	];
	var f = new liwe.form.instance ( 'stats-form-' + dest_div );
	f.hidden ( 'action', 'stats.ajax.graph' );
	f.hidden ( 'module', this.module );
	f.hidden ( 'dest_div_form', dest_div_form );
	f.calendar ( { label: 'Inizio', name: 'log_start' } );
	f.calendar ( { label: 'Fine', name: 'log_end' } );
	f.select ( { label: 'Tipo LOG', name: 'log_type', options: log_types } );
	f.select ( { label: 'Tipo Graph', name: 'gtype', options: gtypes } );
	f.select ( { label: 'Tipo Stats', name: 'event', options: this.events } );

	if ( extras )
	{
		var data = extras [ 'data' ];
		var opts = [];

		opts.push ( { label: '(tutti)', value: '' } );
		data.iterate ( function ( o )
		{
			opts.push ( o );
		} );

		if ( opts.length > 1 )
			f.select ( { label: extras [ 'label' ], name: 'id_ref', options: opts } );
	}

	f.button ( { onclick: "stats._do_graph('" + dest_div + "')", value: 'Visualizza' } );
	f.set ( dest_div );
};

stats._do_graph = function ( dest_div )
{
	var values = liwe.form.get ( 'stats-form-' + dest_div ).get_values ();
	
	stats.ajax ( values, function ( res )
	{
		stats.graph ( values.dest_div_form, values.gtype, res );
	});
};
